package com.wosiliujing.learning.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wosiliujing.learning.entity.TreeNode;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: liujing
 * @date: 2019/5/7 21:19
 * @description:
 */
@UtilityClass
public class TreeUtil {

    /**
     * 构建树
     * @param  treeNodes 所有树节点
     * @param root 跟节点
     * @param <T> treeNode子类
     * @return 组装树
     */
    public <T extends TreeNode> List<T> buildTree(List<T> treeNodes, Object root){
        List<T> trees = new ArrayList<>();
        for(T treeNode : treeNodes){
            if(ObjectUtil.equal(root,treeNode.getParentId())){
                trees.add(findChildren(treeNodes,treeNode));
            }
        }
        return trees;
    }

    /**
     * 递归组装树
     * @param treeNodes 所有树节点
     * @param treeNode 当前树节点
     * @param <T> treeNode子类
     * @return 组装树
     */
    public  <T extends TreeNode> T findChildren(List<T> treeNodes, T treeNode){
        treeNodes.forEach( tree -> {
            if(StrUtil.equals(treeNode.getId(),tree.getParentId())){
                if(ObjectUtil.isNull(treeNode.getChildren())){
                   treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(treeNodes,tree));
            }
        });
        return treeNode;
    }
}
